package com.warframe.alerts;

import com.alibaba.fastjson.JSON;
import com.tools.HibernateUtils;
import com.tools.HttpLocalTools;
import com.tools.StringContent;
import com.tools.StringLocalUtils;
import com.warframe.entity.alerts.AlertsMO;
import com.warframe.entity.database.WikiTranslateEO;
import com.warframe.entity.message.Message;
import com.warframe.message.Executor;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Alerts implements Runnable {

    private static String url = "https://api.warframestat.us/pc/alerts";
    private static String wikitranslateSql = "select * from WikiTranslate a where a.item_en like 'TARGET' order by a.item_cn";
    private Message message;
    private StringBuilder msg;
    private Boolean highSign;

    public Alerts(Message message) {
        this.message = message;
        highSign = false;
        msg = new StringBuilder("Ordis监测到当前警报如下");
    }

    public Alerts(Boolean highSign) {
        this.message = new Message();
        this.highSign = highSign;
        msg = new StringBuilder("Ordis监测到当前警报如下");
    }

    private void getResult() {
        CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建httpClient实例
        HttpGet httpGet = new HttpGet(url); // 创建httpget实例
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        CloseableHttpResponse response = null; // 执行http get请求
        try {
            response = httpClient.execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity = response.getEntity(); // 获取返回实体
        String res = null;
        try {
            res = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<AlertsMO> original = JSON.parseArray(res, AlertsMO.class);
        List<AlertsMO> alertsMOList = new ArrayList<>();
        if (highSign) {
            for (AlertsMO eachMO : original) {
                if (StringContent.ALERTSREWARD.get(eachMO.getRewardTypes().get(0)) == null &&
                        !StringContent.ALERTSHISTORY.contains(eachMO.getId())) {
                    alertsMOList.add(eachMO);
                    StringContent.ALERTSHISTORY.add(eachMO.getId());
                    while (StringContent.ALERTSHISTORY.size() > 10) {
                        StringContent.ALERTSHISTORY.poll();
                    }
                }
            }
        } else {
            alertsMOList.addAll(original);
        }
        for (AlertsMO eachMO : alertsMOList) {
            StringBuilder str = new StringBuilder("\n任务类型 : ");
            str.append(explainType(eachMO.getMission().getType(),
                    eachMO.getMission().isNightmare(), eachMO.getMission().isArchwingRequired()) + "\n");
            str.append("任务地点 : ");
            str.append(explainNode(eachMO.getMission().getNode()) + "\n");
            str.append("星币奖励 : ");
            str.append(eachMO.getMission().getReward().getCredits() + " 星币\n");
            String itemReward = explainReward(eachMO.getMission().getReward());
            if (itemReward != null) {
                str.append("物品奖励 : ");
                str.append(itemReward + "\n");
            }
            if (StringLocalUtils.hasString(eachMO.getEta(), "-")) {
                str.append(eachMO.getEta()
                        .replace("-", "")
                        .replace("m", "分钟")
                        .replace("s", "秒后"));
                str.append("警报开始");
            } else {
                str.append("剩余时间 : ");
                str.append(eachMO.getEta()
                        .replace("m", "分钟")
                        .replace("s", "秒"));
            }
            msg.append(str);
        }
    }

    private String explainType(String type, Boolean nightmare, Boolean archwingRequired) {
        String original = type;
        String result = "TYPENIGHTARCHW";
        String sql = wikitranslateSql.replace("TARGET", original);
        Session session = HibernateUtils.getSessionFactory().openSession();
        SQLQuery sqlQuery = session.createSQLQuery(sql);
        List<WikiTranslateEO> wikiTranslateEOList = sqlQuery.addEntity(WikiTranslateEO.class).list();
        if (wikiTranslateEOList.size() > 0) {
            for (WikiTranslateEO eachEO : wikiTranslateEOList) {
                original = result.replace("TYPE", eachEO.getItemCn());
                break;
            }
        } else {
            original = result.replace("TYPE", "");
            Executor.getCQ().sendPrivateMsg(StringContent.OWNER, "未找到的任务类型 : " + original);
        }
        if (nightmare) {
            original = original.replace("NIGHT", "(噩梦)");
        } else {
            original = original.replace("NIGHT", "");
        }
        if (archwingRequired) {
            original = original.replace("ARCHW", "(需要翅膀)");
        } else {
            original = original.replace("ARCHW", "");
        }
        session.close();
        return original;
    }

    private String explainNode(String node) {
        String original = node;
        node = node.substring(node.indexOf("(") + 1, node.lastIndexOf(")"));
        String sql = wikitranslateSql.replace("TARGET", node);
        Session session = HibernateUtils.getSessionFactory().openSession();
        SQLQuery sqlQuery = session.createSQLQuery(sql);
        List<WikiTranslateEO> wikiTranslateEOList = sqlQuery.addEntity(WikiTranslateEO.class).list();
        if (wikiTranslateEOList.size() > 0) {
            for (WikiTranslateEO eachEO : wikiTranslateEOList) {
                original = original.replace(node, eachEO.getItemCn());
                break;
            }
        } else {
            Executor.getCQ().sendPrivateMsg(StringContent.OWNER, "未识别到的警报类型：" + original);
        }
        session.close();
        return original;
    }

    private String explainReward(AlertsMO.Mission.Reward reward) {
        StringBuilder stringBuilder = new StringBuilder();
        String itemString = reward.getItemString();
        String credits = reward.getCredits().toString();
        if (itemString.length() > 0) {
            String number;
            if (StringLocalUtils.hasDigit(itemString)) {
                number = itemString.substring(0, itemString.indexOf(" ") + 1);
                itemString = itemString.substring(itemString.indexOf(" ") + 1, itemString.length());
                Session session = HibernateUtils.getSessionFactory().openSession();
                SQLQuery sqlQuery = session.createSQLQuery(wikitranslateSql.replace("TARGET", itemString));
                List<WikiTranslateEO> wikiTranslateEOList = sqlQuery.addEntity(WikiTranslateEO.class).list();
                if (wikiTranslateEOList.size() > 0) {
                    for (WikiTranslateEO eachEO : wikiTranslateEOList) {
                        return number + eachEO.getItemCn();
                    }
                } else {
                    Executor.getCQ().sendPrivateMsg(StringContent.OWNER, "未查询到的警报奖励" + reward.getItemString());
                    return number + itemString;
                }
                session.close();
            } else {
                if (StringLocalUtils.hasString(itemString, StringContent.BULEPRINT)) {
                    itemString = itemString.substring(0, itemString.lastIndexOf(" "));
                }
                Session session = HibernateUtils.getSessionFactory().openSession();
                SQLQuery sqlQuery = session.createSQLQuery(wikitranslateSql.replace("TARGET", itemString));
                List<WikiTranslateEO> wikiTranslateEOList = sqlQuery.addEntity(WikiTranslateEO.class).list();
                if (wikiTranslateEOList.size() > 0) {
                    for (WikiTranslateEO eachEO : wikiTranslateEOList) {
                        return eachEO.getItemCn();
                    }
                } else {
                    Executor.getCQ().sendPrivateMsg(StringContent.OWNER, "未查询到的警报奖励" + reward.getItemString());
                    return itemString;
                }
                session.close();
            }
        }
        return null;
    }


    @Override
    public void run() {
        getResult();
        message.setMsg(msg.toString());
        if (msg.length() > 15) {
            if (highSign) {
                for (Long groupId : StringContent.SCHEDULEDGROUP) {
                    message.setGroupId(groupId);
                    message.setSign(StringContent.SENDGROUP);
                    Executor.getInstance().pushMsg(message);
                }
            } else {
                message.setSign(StringContent.SENDPERSON);
                Executor.getInstance().pushMsg(message);
            }
        }
    }
}
